package com.elite.controller;

import com.alibaba.fastjson.JSON;
import com.elite.entity.*;
import com.elite.service.AdressService;
import com.elite.service.GoodsService;
import com.elite.service.GoodsorderService;
import com.elite.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2017/2/18.
 */
@RestController
@RequestMapping("/shopping")
public class ShoppingCartController {


    @Autowired
    private HttpSession session;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AdressService adressService;
    @Autowired
    private GoodsorderService goodsorderService;


    private static final Logger LOGGER = Logger.getLogger(String.valueOf(ShoppingCartController.class));


    /**
     * 在购物车里显示该用户所需的购物商品
     * @return
     */
    @RequestMapping(value = "/showCart",produces = "text/html;charset=UTF-8" )
    @ResponseBody
    public String showCart(){

        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        User user = null;
        try {
            user = (User) session.getAttribute("loginUser");
        } catch (NullPointerException e){
            e.printStackTrace();
        }

        if (user != null){

            Integer userId = user.getUserId();

            List<ShoppingCart> shoppingCarts = null;
            try {
                shoppingCarts = shoppingCartService.selectByUserId(userId);
            } catch (NullPointerException e){
                e.printStackTrace();
            }

            if (shoppingCarts != null && shoppingCarts.size() != 0){

                for (ShoppingCart shoppingCart : shoppingCarts){

                    Goods goods = null;
                    try {
                        goods = goodsService.selectByPrimaryKey(shoppingCart.getGoodsId());
                    }catch (NullPointerException e){
                        e.printStackTrace();
                    }
                    if (goods != null) {
                        if (goods.getGoodsSize() > 0){

                            Map<String,Object> map = new HashMap<String, Object>();
                            map.put("shoppingcartId",shoppingCart.getShoppingcartId());
                            map.put("goodsName",shoppingCart.getGoodsName());
                            map.put("fileUrl",shoppingCart.getFileUrl());
                            map.put("goodsIntroducts",shoppingCart.getGoodsIntroducts());
                            map.put("goodsCity",shoppingCart.getGoodsCity());
                            map.put("goodsSize",shoppingCart.getGoodsSize());
                            map.put("totalprice",shoppingCart.getTotalprice());
                            map.put("goodsPrice",goods.getGoodsPrice());
                            map.put("totalSize",goods.getGoodsSize());
                            mapList.add(map);

                        }else {
                            deleteCart(shoppingCart.getShoppingcartId());
                        }
                    }
                }

            }

        }else {
            try {
                response.sendRedirect(request.getContextPath() + "/resources/seller_login.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return JSON.toJSON(mapList).toString();
    }

    /**
     * 在购物车页面删除商品
     * @param shoppingcartId
     * @return
     */
    @RequestMapping(value = "/deleteCart",method = RequestMethod.POST)
    @ResponseBody
    public String deleteCart(Integer shoppingcartId){

        shoppingCartService.deleteShoppingCart(shoppingcartId);

        return JSON.toJSON("true").toString();
    }

    /**
     * 更新购物车
     * @param shoppingcartId
     * @param goodsSize
     * @param totalprice
     */
    @RequestMapping(value = "/updateCart",method = RequestMethod.POST)
    @ResponseBody
    public void updateCart(Integer shoppingcartId,Integer goodsSize,Float totalprice){

        ShoppingCart shoppingCart = shoppingCartService.selectByPrimaryKey(shoppingcartId);
        Goods goods = null;
        try {
            goods = goodsService.selectByPrimaryKey(shoppingCart.getGoodsId());
        }catch (NullPointerException e){
            e.printStackTrace();
        }

        if (goods != null) {
            if (goods.getGoodsSize() > 0){

                if (goodsSize != null && totalprice != null){

                    if (goodsSize < goods.getGoodsSize() && goodsSize > 0 && totalprice != 0){

                        shoppingCart.setGoodsSize(goodsSize);
                        shoppingCart.setTotalprice(totalprice);
                        shoppingCartService.updateByPrimaryKey(shoppingCart);

                    }
                }

            }
        }

    }


    /**
     * 购物车里的支付
     * @param in
     * @return
     */
    @RequestMapping(value = "/payCart",method = RequestMethod.POST)
    @ResponseBody
    public String payCart(String in){

        int count = 0;
        int count1 = 0;
        String result = null;
        String[] arr1 = in.split(",");
        int[] arr = new int[arr1.length];
        for (int i = 0; i < arr1.length; i++) {
            arr[i] = Integer.parseInt(arr1[i]);
        }

        for (int shoppingcartId:arr){
            if (shoppingcartId != 0){
                ShoppingCart shoppingCart = shoppingCartService.selectByPrimaryKey(shoppingcartId);
                Goods goods = null;
                try {
                    goods = goodsService.selectByPrimaryKey(shoppingCart.getGoodsId());
                }catch (NullPointerException e){
                    e.printStackTrace();
                }
                List<Adress> adresses = null;
                try {
                    adresses = adressService.selectAddressById(shoppingCart.getUserId());
                }catch (NullPointerException e){
                    e.printStackTrace();
                }
                int index1 = 0;
                if (adresses != null && adresses.size() != 0) {
                    index1 = (int) (Math.random()*adresses.size());
                }
                Adress adress = null;
                if (adresses != null && adresses.size() != 0) {
                    adress = adresses.get(index1);
                }

                Goodsorder goodsorder = new Goodsorder();
                if (goods != null) {
                    if (goods.getGoodsSize() > 0 && shoppingCart.getGoodsSize() <= goods.getGoodsSize()){

                        goods.setGoodsPrice(goods.getGoodsPrice());
                        goods.setGoodsIntroducts(goods.getGoodsIntroducts());
                        goods.setGoodsSchool(goods.getGoodsSchool());
                        goods.setGoodsSize(goods.getGoodsSize()-shoppingCart.getGoodsSize());
                        goods.setGoodsUnit(goods.getGoodsUnit());
                        goodsService.updateByPrimaryKey(goods);

                        if (adress != null){

                            goodsorder.setGoodsId(shoppingCart.getGoodsId());
                            goodsorder.setUserId(shoppingCart.getUserId());
                            goodsorder.setSellerId(goods.getSellerId());
                            goodsorder.setAdressId(adress.getAdressId());
                            goodsorder.setGoodsorderCount(shoppingCart.getGoodsSize());
                            goodsorder.setGoodsorderPrice(shoppingCart.getTotalprice());
                            goodsorder.setGoodsorderStatus(0);
                            goodsorder.setGoodsAdress(adress.getGoodsAdress());
                            goodsorderService.addGoodsorder(goodsorder);

                            deleteCart(shoppingcartId);
                            count++;
                        }
                    } else {
                        deleteCart(shoppingcartId);
                        count1++;
                    }
                }
            }
        }



        if (count != 0){

            result = "true";

        }else {
            result = "false";
        }


        return JSON.toJSON(result).toString();

    }


    /**
     * 商品详情页的支付
     * @param goodsId
     * @param goodsSize
     * @return
     */
    @RequestMapping(value = "/payCart1",method = RequestMethod.POST)
    @ResponseBody
    public String payCart1(Integer goodsId,Integer goodsSize){

        String result = null;
        Goods goods = null;
        try {
            goods = goodsService.selectByPrimaryKey(goodsId);
        }catch (NullPointerException e){
            e.printStackTrace();
        }

        User user = null;
        try {
            user = (User) session.getAttribute("loginUser");
        } catch (NullPointerException e){
            e.printStackTrace();
        }

        if (user != null){

            if (goods != null){

                if (goods.getGoodsSize() >0 && goodsSize != null){

                    Integer userId = user.getUserId();

                    List<Adress> adresses = null;
                    try {
                        adresses = adressService.selectAddressById(userId);
                    }catch (NullPointerException e){
                        e.printStackTrace();
                    }
                    int index1 = 0;
                    if (adresses != null && adresses.size() != 0) {
                        index1 = (int) (Math.random()*adresses.size());
                    }
                    Adress adress = null;
                    if (adresses != null && adresses.size() != 0) {
                        adress = adresses.get(index1);
                    }

                    if (goodsSize <= goods.getGoodsSize()){

                        goods.setGoodsPrice(goods.getGoodsPrice());
                        goods.setGoodsIntroducts(goods.getGoodsIntroducts());
                        goods.setGoodsSchool(goods.getGoodsSchool());
                        goods.setGoodsSize(goods.getGoodsSize() - goodsSize);
                        goods.setGoodsUnit(goods.getGoodsUnit());
                        goodsService.updateByPrimaryKey(goods);

                        if (adress != null) {

                            Goodsorder goodsorder = new Goodsorder();
                            goodsorder.setGoodsId(goodsId);
                            goodsorder.setUserId(userId);
                            goodsorder.setSellerId(goods.getSellerId());
                            goodsorder.setAdressId(adress.getAdressId());
                            goodsorder.setGoodsorderCount(goodsSize);
                            goodsorder.setGoodsorderPrice(goodsSize * goods.getGoodsPrice());
                            goodsorder.setGoodsorderStatus(0);
                            goodsorder.setGoodsAdress(adress.getGoodsAdress());
                            goodsorderService.addGoodsorder(goodsorder);

                            result = "true";

                        }
                    } else {

                        result = "false";
                    }

                }
            }
        }

        return JSON.toJSON(result).toString();
    }

}
